package org.grow.jssp.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;

@Controller
public class DownloadController {
    @GetMapping("/repository")
    public ModelAndView repository(HttpServletRequest request) {
//        代表着变量，表示电脑上的文件夹目录
        String target = "D:\\share";
        System.out.println(target);
        File file = new File(target);
        File[] oldList = file.listFiles();
//        过滤文件夹
        ArrayList<String> newList = new ArrayList<>();
        for (int i = 0; i < oldList.length; i++) {
            File item = oldList[i];
            if (item.isFile()) newList.add(item.getName());
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("repository");
        modelAndView.addObject("fileList", newList);
        return modelAndView;
    }

    @GetMapping("/download/{filename}")
    public void download(@PathVariable String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String target = "D:\\share";
        String address = target + File.separator + filename;
        System.out.println(address);
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(address));
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] buffer = new byte[1024 * 1024];
        int len;
        while ((len = in.read(buffer)) > 0) {
            outputStream.write(buffer, 0, len);
        }
        in.close();
        outputStream.close();
    }

}
